<?php
// +----------------------------------------------------------------------
// | ebSIG
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.ebsig.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: liudaojian <liudaojian@ebsig.com>
// +----------------------------------------------------------------------

/**
 * 易事多项目 - CRM接口类
 * @author   liudaojian <liudaojian@ebsig.com>
 * @version 1.0
 */

namespace App\Service\Rpc\Crm;

use Carbon\Carbon;

use App\Service\HttpService;

use App\Models\Log\LogEaiCrm; //接口日志

use App\Models\Customer\Customer;  //会员

use Illuminate\Support\Facades\Redis as Redis;

/**
 *      @方法  	request			    请求接口
 *      @方法  	customerQuery		查询会员信息
 *      @方法  	customerEdit		修改会员信息
 *      @方法  	openCard			开卡
 *      @方法  	bindCard			绑卡
 *      @方法  	pointsQuery			获取总积分
 *      @方法  	pointsAdd			通过卡号增加积分
 *      @方法  	pointsReduction		通过卡号减少积分
 *      @方法  	pointsLogs			积分变更流水
 *      @方法  	accountQuery		卡余额查询
 *      @方法  	consumption			卡余额消费(支付)
 *      @方法  	recharge			卡余额充值
 *      @方法  	accountLogs			卡消费流水(余额变更记录)
 */

class YsdCrm
{

    /**
     * 接口请求地址
     */
    private $http_url = 'http://125.45.93.207:8380/hdcard-services/api/';

    /**
     * 项目ID
     */
    private $card_id = '9573';

    /**
     * 门店代码
     */
    private $store_code = '6666';

    /**
     * 账户类型
     */
    private $account_access_type = 2;

    /**
     * 应用名称
     */
    private $app_name = 'HDCARD';


    /**
     * 组织代码
     */
    private $org_code = '6666';


    /**
     * 组织代码名称
     */
    private $org_name = '';


    //用户会员名
    private $custID = 0;


    //会员号
    private $card_no = 0;


    /**
     * 请求接口，并保存日志
     * @param string $request_url 请求链接
     * @param string $api_name 接口名称
     * @param array $get_data get请求数据
     * @param array $post_data post请求数据
     * @param string $request_way 请求方式
     *
     * @return array('code'=>'','message'=>'','data'=>'')
     */
    public function request($request_url, $api_name, $get_data = array(), $post_data = array(), $request_way = 'get') {

        $Client = new HttpService();

        $start_time = microtime(true);

        //连接接口参数
        $http_opts = [
            CURLOPT_TIMEOUT => 30,
            CURLOPT_CONNECTTIMEOUT => 15,
            CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
            CURLOPT_USERPWD => 'guest:guest',
            CURLOPT_HTTPHEADER => array('Accept: application/json', 'Content-Type: application/json')
        ];

        //请求接口
        if ( $request_way == 'get' ) {  //get方式请求

            if ( !empty($get_data) ) {
                $get_data_str = '?' . http_build_query($get_data);
            } else {
                $get_data_str = $get_data;
            };
            $http_result = $Client->get($request_url . $get_data_str, $http_opts);

        } else if ( $request_way == 'post:json' ) {

            if (!empty($get_data)) {
                $request_url .= '?' . http_build_query($get_data);
            }
            $post_data_json = json_encode($post_data);
            $http_result = $Client->post($request_url, $post_data_json, $http_opts);

        } else if ( $request_way == 'put:json' ) {

            if ( !empty( $get_data ) ) {
                $request_url .= '?' . http_build_query($get_data);
            }
            $post_data_json = json_encode($post_data);

            if ( $api_name == 'openCard'||$api_name == 'bindCard' ) {
                $http_result = $Client->put($request_url, $post_data_json, $http_opts);
                //处理返回开卡接口/注册会员返回数据不为科学计数法
                if ( is_float( $http_result['data'] ) ){
                    $http_result['data'] = number_format($http_result['data'], 0, '', '');
                }
            } else {
                $http_result = $Client->put($request_url, $post_data_json, $http_opts);
            }

        } else {
            $http_result = $Client->post($request_url, $post_data, $http_opts);
        }

        //接口请求结束时间
        $end_time = microtime(true);

        //接口请求返回参数
        if ( isset( $http_result['data'] ) && is_array( $http_result['data'] ) &&  isset( $http_result['data']['error_code'] ) ) {
            $return_data = [
                'code' => 404,
                'message' => $http_result['data']['message']
            ];
            //20x http 请求正常但无返回 （如充值准备前的操作）
        } else if (!in_array($http_result['code'], [200, 201, 202, 203, 204, 205])) {
            $return_data = [
                'code' => $http_result['code'],
                'message' => $http_result['message']
            ];
        } else {
            $return_data = [
                'code' => 200,
                'message' => 'ok',
                'data' => isset( $http_result['data'] ) ? $http_result['data'] : 'null'
            ];
        }

        //会员信息
        $cust_array = [];
        if ( $this->custID ) {
            $cust_array = Customer::where(['custID' => $this->custID])->first();
        }

        if ( empty( $cust_array ) && $this->card_no ) {
            $cust_array = Customer::where(['cardNo' => $this->card_no])->first();
        }

        //记录日志
        $log_obj = new LogEaiCrm();
        $log_obj->uuid = makeUuid();
        $log_obj->timeStamp = Carbon::now();
        $log_obj->creator = 'YSD';
        $log_obj->createTime = Carbon::now();
        $log_obj->api_name = $api_name;
        $log_obj->pcustID = isset($cust_array['pcustID']) ? $cust_array['pcustID'] : 0;
        $log_obj->custID = isset($cust_array['custID']) ? $cust_array['custID'] : 0;
        $log_obj->request_status = $return_data['code'] == 200 ? 2 : 3;
        if( !empty($get_data) && !empty($post_data) ){
            $log_obj->request_data = print_r(array_merge($get_data, $post_data), true);
        } elseif ( !empty($get_data) ) {
            $log_obj->request_data = print_r($get_data, true);
        } else {
            $log_obj->request_data = print_r($post_data, true);
        }
        $log_obj->return_data = print_r( $http_result, true );
        $log_obj->return_code = $return_data['code'] ? $return_data['code'] : 404;
        $log_obj->return_msg = $return_data['message'];
        $log_obj->exec_time = ($end_time - $start_time) * 1000;
        $log_obj->save();

        return $return_data;

    }


    //调整组织代码数据（有选店传选店，有传入指定门店传指定门店，最终还没有则取用默认组织代码—虚拟门店代码）
    public function adjustOrgCode( $args_array ) {

        if ( isset( $args_array['session_id']) && !empty( $args_array['session_id'] ) ) {
            //获取选店信息
            $select_mall = redisTransformation(Redis::get($args_array['session_id'] . 'CUST_SELECTMALL'));
            if( !empty($select_mall) ){
                $this->org_code = $select_mall['mallCode'];
                $this->org_name = $select_mall['mallName'];
            }
        }

        //若有传入门店号，则替换传入的门店
        if( isset( $args_array['mallCode']) && !empty( $args_array['mallCode'] ) ){
            $this->org_code = $args_array['mallCode'];
        }

        //若有传入门店名称，则替换传入的门店名称
        if( isset( $args_array['mallName']) && !empty( $args_array['mallName'] ) ) {
            $this->org_name = $args_array['mallName'];
        }

    }


    /**
     * 根据手机号查询卡资料
     * @param array       $args_array                     参数数组
     *        string      $args_array['pcustID']          会员号              必须
     *        string      $args_array['mobilenum']        手机号              必须
     *
     * @return array('code'=>'','message'=>'','data'=>'')
     */
    public function customerQuery( $args_array ) {

        if( !isset( $args_array['mobilenum'] ) || empty( $args_array['mobilenum'] ) ) {
            return [ 'code'=>400, 'message'=>'手机号不能为空'];
        }

        $this->custID = $args_array['mobilenum'];

        //请求地址
        $request_url = $this->http_url."member/query_by_mobilenum";

        //设置接口请求参数
        $params = [
            'mobilenum' => $args_array['mobilenum']
        ];

        //调用接口
        $request_res = $this->request( $request_url, 'customerQuery', $params , '' , 'get' );

        if ( $request_res['code'] != 200 ) {
            return ['code' => $request_res['code'],'message' => $request_res['message']];
        }

        $return_array = [
            'memberCode' => $request_res['data']['code'],     //会员号
            'cardNum' => $request_res['data']['originCode'], //卡号
            'cardNo' => $request_res['data']['originCode'],   //卡号
            'cardType' => $request_res['data']['memberGrade']['code'],  //卡类型code
            'cardName' => $request_res['data']['memberGrade']['name'],  //卡类型名称
        ];

        return ['code' => 200, 'message' => 'ok', 'data' => $return_array ];

    }


    /**
     * 会员基本信息修改
     *  @param	array	    $args_array		            请求参数
     * 		    string		$args_array['openId']	    微信openid	必选
     * 		    string		$args_array['custID']	    会员名		可选
     * 		    string		$args_array['pcustID']	    会员号		必选
     *          string		$args_array['custname']	    姓名		    可选
     *          string		$args_array['sexy']	        性别		0.未知  1.男  2.女 可选
     *          string		$args_array['birthday']	    生日		如“1990-09-10”可选
     * 		    string		$args_array['mobile']	    手机号		可选
     *          string		$args_array['email']	    邮箱		    可选
     * 		    string		$args_array['identityCard']	身份证      可选
     *
     * @return array('code'=>'','message'=>'','data'=>'')
     */
    public function customerEdit( $args_array ){


        $api_result = $this->queryBuId($args_array);

        if( $api_result['code'] != 200 ){
            return [ 'code' => $api_result['code'], 'message' => $api_result['message']];
        }

        if ( isset( $args_array['custID'] ) && !empty( $args_array['custID'] ) ) {
            $this->custID = $args_array['custID'];
        }

        if ( isset( $args_array['cardNo'] ) && !empty( $args_array['cardNo'] ) ) {
            $this->card_no = $args_array['cardNo'];
        }

        //修改会员信息
        $api_result['data']['name'] = !empty( $args_array['custname']) ? $args_array['custname'] : $args_array['mobile'] ;                 //会员姓名
        $api_result['data']['cellPhone'] = isset($args_array['mobile']) ? $args_array['mobile'] : '';                   //手机
        $api_result['data']['email'] = isset($args_array['email']) ? $args_array['email'] : '';                    //邮箱
        if(isset($args_array['birthday']) && !empty($args_array['birthday'])){
            $api_result['data']['birthday'] = $args_array['birthday'] . ' 00:00:00';                                   //生日
        }
        $api_result['data']['qq'] = isset($args_array['QQ']) ? $args_array['QQ'] : '';                                //QQ号

        //性别转换成海鼎需要的参数
        if ( isset($args_array['sexy']) && $args_array['sexy'] == 1 ) {
            $api_result['data']['sex'] = 'male';
        } else if (isset($args_array['sexy']) && $args_array['sexy'] == 2 ) {
            $api_result['data']['sex'] = 'female';
        } else {
            $api_result['data']['sex'] = 'privacy';
        }


        //调整组织代码
        $this->adjustOrgCode($args_array);

        //设置接口url请求参数
        $params = [
            'xid' => time(),
            'orgcode' => $this->org_code
        ];

        //请求地址
        $request_url = $this->http_url."member/modify";

        //调用接口
        $request_res =  $this->request( $request_url, 'customerEdit', $params , $api_result['data'] , 'post:json' );

        if ( $request_res['code'] != 200 ) {
            return ['code' => $request_res['code'], 'message' => $request_res['message']];
        }

        return ['code' => 200, 'message' => 'ok'];

    }


    /**
     * 开卡接口
     * @param array     $args_array	                请求参数
     *        string    $args_array['pcustID']       会员号              必须
     *        string    $args_array['mobile']        手机号              必须
     *
     * @return array(code=>'', message=>'', data=>array(cardNo=>卡号 , cardType=>卡类型) )
     */
    public function openCard( $args_array ){

        //参数校验
        if (!isset( $args_array['mobile']) || empty($args_array['mobile'])) {
            return ['code' => 400 , 'message' => '手机号不能为空'];
        }

        $this->custID = $args_array['mobile'];

        //调整组织代码
        $this->adjustOrgCode($args_array);

        //设置接口url请求参数
        $business_params = [
            'xid'     => time(),
            'orgcode' => $this->org_code
        ];

        //会员注册参数
        $request_params = [
            'name' => empty($args_array['custname']) ? $args_array['mobile'] : $args_array['custname'],
            'cellPhone' => $args_array['mobile'],
            'org'=>['name' => $this->org_name],
            'memberSource' => ['code' => 'WDH'],
        ];

        //请求地址
        $request_url = $this->http_url."member/regist";

        //调用接口
        $request_res = $this->request( $request_url, 'openCard', $business_params , $request_params , 'put:json' );

        if ( $request_res['code'] != 200 || empty($request_res['data']) ) {
            return ['code' => $request_res['code'], 'message' => $request_res['message']];
        }

        //调用绑定接口
        $args_array = [
            'cardNo' => $request_res['data'],
            'openId' => $args_array['mobile']
        ];

        $this->deliverBindCust($args_array);

        $return_array = [
            'cardNo' => $request_res['data'],         //卡号
            'cardType' => ''                         //卡类型
        ];

        return ['code' => 200, 'message' => 'ok','data' => $return_array];

    }



    /**
     * 会员绑卡接口
     * @param array     $args_array	                请求参数
     *        string    $args_array['pcustID']       会员号             必须
     *        string    $args_array['mobile']        手机号             必须
     *        string    $args_array['cardNo']        卡号               必须
     *
     * @return array(code=>'', message=>'' )
     */
    public function bindCard( $args_array ){

        //校验参数
        if (!isset($args_array['mobile']) || empty($args_array['mobile'])) {
            return ['code' => 400 , 'message' => '手机号不能为空'];
        }

        if (!isset($args_array['cardNo']) || empty($args_array['cardNo'])) {
            return ['code' => 400 , 'message' => 'cardNo不能为空'];
        }

        $this->custID = $args_array['mobile'];

        //调整组织代码
        $this->adjustOrgCode($args_array);

        //设置接口请求参数
        $request_params =[
            'xid' => time(),
            'time'  => time(),
            'storeCode' =>$this->store_code,
            'cardId' =>$this->card_id,
            'openId' => $args_array['mobile'],
            'mobile' => $args_array['mobile'],
            'cardNo' => $args_array['cardNo']
        ];

        //请求地址
        $request_url = $this->http_url."wx/bind_card2";

        //调用接口
        $request_res =  $this->request( $request_url, 'bindCard', '', $request_params,  'post:json' );

        if ( $request_res['code'] != 200 || isset( $request_res['data'] )) {
            return ['code' =>  $request_res['code'] , 'message' =>  $request_res['message'] ];
        }

        $res = $request_res['data']['records'][0];

        $return_array = [
            'entityCardNo' => isset($res['cardNum']) ? $res['cardNum'] : '',
            'cardNo'       => isset($res['member']['code']) ? $res['member']['code'] : '',
            'cardType'     => isset($res['cardType']['code']) ? $res['cardType']['code'] : ''
        ];

        return ['code' => 200, 'message' => 'ok', 'data' => $return_array ];

    }



    /**
     * 查询账户积分信息
     *@param	array	$args_array		请求参数
     *          string  $args_array['pcustID']       会员号             必须
     * 		    string	$args_array['cardNo']	     卡号  	            必选
     *
     * @return array(code =>'', message=>'' ,  'data' => array('points' => '') )
     */
    public function pointsQuery( $args_array ){

        //校验参数
        if (!isset($args_array['cardNo']) || empty($args_array['cardNo'])) {
            return ['code'=>400 , 'message'=>'卡号不能为空'];
        }

        $this->card_no = $args_array['cardNo'];

        //设置接口url请求参数
        $business_params = [
            'account_accesscode' => (string)$args_array['cardNo'],
            'account_accesstype' => $this->account_access_type
        ];

        //请求地址
        $request_url = $this->http_url."desaccount/query";

        //调用接口
        $request_res =  $this->request( $request_url, 'pointsQuery', $business_params , '' , 'get' );

        if ( $request_res['code'] != 200 ) {
            return ['code' => $request_res['code'] , 'message' =>  $request_res['message']];
        }

        $return_array = [
            'points' => isset($request_res['data']['score']) ? $request_res['data']['score'] : 0
        ];

        return ['code' => 200, 'message' => 'ok', 'data' => $return_array];

    }


    /**
     * 添加积分
     * @param  array	$args_array	            请求参数
     * 		   string	$args_array['cardNo']   卡号           必传
     *         int      $args_array['score']     积分值         必传
     *         string   $params['remark']       备注           非必传
     *
     * @return  array('code'=>'','message'=>'');
     */
    public function pointsAdd( $args_array ){

        //校验参数
        if ( !isset($args_array['cardNo']) || empty($args_array['cardNo']) ) {
            return [ 'code' => 400 , 'message' => '账户识别码不能为空' ];
        }

        if( !isset($args_array['code']) || empty($args_array['code']) ){
            $args_array['code'] = 101;
        }

        if( !isset($args_array['points']) || empty($args_array['points']) ){
            return [ 'code'=>400 , 'message'=>'积分值不能为空' ];
        }

        $this->card_no = $args_array['cardNo'];

        //调整组织代码
        $this->adjustOrgCode($args_array);

        //设置接口url请求参数
        $business_params = [
            'xid'     => time(),
            'orgcode' => $this->org_code,
            'account_accesscode' => (string)$args_array['cardNo'],
            'account_accesstype' => $this->account_access_type
        ];

        //设置接口请求参数
        $request_params = [
            'subjectAccounts' => [
                [
                    'remark' => isset($args_array['remark'])?$args_array['remark']:'',
                    'scoreType' => ['code' => '-',],
                    'scoreSubject' => ['code' =>  $args_array['code']],
                    'score' => $args_array['points']
                ]
            ]
        ];

        //请求地址
        $request_url = $this->http_url."/scoreaccount/inc";

        //调用接口
        $request_res = $this->request( $request_url, 'pointsAdd', $business_params , $request_params , 'post:json' );

        if ( $request_res['code'] != 200 ) {
            return ['code' => $request_res['code'] , 'message' =>  $request_res['message']];
        }

        return [ 'code' => 200, 'message' => 'ok'];

    }


    /**
     * 扣减积分
     * @param  array	$args_array	            请求参数
     * 		   String	$args_array['cardNo']   卡号           必传
     *         Int      $args_array['score']     积分值         必传
     *         String   $params['remark']       备注           非必传
     *
     * @return  array('code'=>'','message'=>'');
     */
    public function pointsReduction( $args_array ){

        //校验参数
        if (!isset($args_array['cardNo']) || empty($args_array['cardNo'])) {
            return [ 'code'=>400 , 'message'=>'卡号不能为空' ];
        }

        if(!isset($args_array['code']) || empty($args_array['code'])){
            $args_array['code'] = 107;
        }

        if( !isset($args_array['points']) || empty($args_array['points']) ){
            return [ 'code'=>400 , 'message'=>'积分值不能为空' ];
        }

        $this->card_no = $args_array['cardNo'];

        //调整组织代码
        $this->adjustOrgCode($args_array);

        //设置接口url请求参数
        $business_params = [
            'xid'     => time(),
            'orgcode' => $this->org_code,
            'account_accesscode' => (string)$args_array['cardNo'],
            'account_accesstype' => $this->account_access_type
        ];

        //设置接口请求参数
        $request_params = [
            'subjectAccounts' => [
                [
                    'remark' => isset($args_array['remark'])?$args_array['remark']:'',
                    'scoreType' => ['code' => '-'],
                    'scoreSubject' => ['code' =>  $args_array['code']],
                    'score' => $args_array['points']
                ]
            ]
        ];

        //请求地址
        $request_url = $this->http_url."scoreaccount/dec";

        //调用接口
        $request_res =  $this->request( $request_url, 'pointsReduction', $business_params , $request_params , 'post:json' );

        if ( $request_res['code'] != 200 ) {
            return ['code' => $request_res['code'] , 'message' =>  $request_res['message']];
        }

        return [ 'code' => 200, 'message' => 'ok'];

    }


    /**
     * 会员账户积分变更记录
     * @param  array	$args_array	            请求参数
     *         string	$args_array['cardNo']   卡号               必传
     *         int      $args_array['page']      页码,第一页默认0    必传
     *         int      $params['rp']     每页条数           可填
     *
     * @return array
     */
    public function pointsLogs( $args_array ){

        //校验参数
        if (!isset($args_array['cardNo']) || empty($args_array['cardNo'])) {
            return [ 'code'=>400 , 'message'=>'卡号不能为空' ];
        }

        $this->card_no = $args_array['cardNo'];

        //设置接口url请求参数
        $business_params = [
            'begin_trandate' =>  '2015-01-01',
            'end_trandate' => date('Y-m-d'),
            'account_accesscode' => (string)$args_array['cardNo'],
            'account_accesstype' => $this->account_access_type
        ];

        //请求地址
        $request_url = $this->http_url."scorehst/query";

        //参入参数
        $request_params = [
            'orders'=>[
                [
                    'field'=>'tranTime',
                    'direction'=>'desc'
                ]
            ],
            'pageSize'=> isset($args_array['rp']) && !empty($args_array['rp']) ? $args_array['rp'] : 10,
            'page'=> isset($args_array['page']) && !empty($args_array['page']) ? intval($args_array['page'])-1 : 0
        ];

        //调用接口
        $request_res =  $this->request( $request_url, 'pointsLogs', $business_params , $request_params , 'post:json' );

        if ( $request_res['code'] != 200 ) {
            return ['code' => $request_res['code'] , 'message' =>  $request_res['message']];
        }

        //页码
        $return_array = [
            'page'  => intval($request_res['data']['paging']['page'])+1,
            'pageSize'  => $request_res['data']['paging']['pageSize'],
            'pageCount'=>$request_res['data']['paging']['pageCount'],
            'count' => isset($request_res['data']['paging']['recordCount'] ) && !empty($request_res['data']['paging']['recordCount']) ? $request_res['data']['paging']['recordCount'] : 0,
        ];

        foreach( $request_res['data']['records'] as $key=>$value ){

            $return_array['data'][] = [
                'createTime'  => $value['created'],                 //时间
                'changeAccount' => abs( $value['occur'] ),          //增加或减少的积分
                'code' => $value['scoreSubject']['code'],           //消费代码
                'remark' => empty($value['remark']) ? $value['scoreSubject']['name'] : $value['remark'],    //消费名称、备注
                'storeName' => $value['store']['name'],             //店名称
                'storeCode' => $value['store']['code'],             //店号
                'oldScore' => $value['oldScore'] ,                  //原始积分
                'changeType' => $value['occur']>0 ? 1: 0 ,          //状态 ,1:增加积分  0: 减少积分
            ];
        }

        return ['code' => 200, 'message' => 'ok', 'data' => $return_array ];

    }



    /**
     * 查询卡账户余额信息
     *@param	array	$args_array		请求参数
     * 		    string	$args_array['cardNo']	卡号  	必选
     *
     * @return array(code =>'', message=>'' ,  'data' => array('balance' => '') )
     */
    public function accountQuery( $args_array ){

        if ( !isset( $args_array['cardNo'] ) || empty( $args_array['cardNo'] ) ) {
            return [ 'message'=>'卡号不能为空' , 'code'=>400 ];
        }

        $this->card_no = $args_array['cardNo'];

        //请求地址
        $request_url = $this->http_url."desaccount/query";

        //设置接口请求参数
        $business_params = [
            'account_accesscode' => (string)$args_array['cardNo'],
            'account_accesstype' => $this->account_access_type
        ];

        //调用接口
        $request_res =  $this->request( $request_url, 'balanceQuery', $business_params , '' , 'get' );

        if ( $request_res['code'] != 200 ) {
            return ['code' => $request_res['code'] , 'message' =>  $request_res['message']];
        }

        return ['code' => 200, 'message' => 'ok', 'data' => [ 'balance' => $request_res['data']['balance']]];

    }


    /**
     * 会员账户余额充值
     * @param array $args_array
     * @return array
     */
    public function recharge( $args_array ){

        if (isset($args_array['cardNo']) && empty($args_array['cardNo'])) {
            return [ 'code'=>400 , 'message'=>'卡号不能为空' ];
        }

        if (!isset($args_array['amount']) || !$args_array['amount']) {
            return [ 'code' => 400 , 'message' => '充值金额不能为空' ];
        }

        if (!isset($args_array['tranId']) || !$args_array['tranId']) {
            $args_array['tranId'] = time();
        }

        $this->card_no = $args_array['cardNo'];

        //调用充值准备接口
        $result_array = $this->rechargePrepare($args_array);

        if ( $result_array['code'] != 200 ) {
            return ['code' => $result_array['code'],'message' => $result_array['message']];
        }

        //调用充值确认接口
        $result_array = $this->rechargeConfirm($args_array);


        if( $result_array['code'] != 200 ) {
            return ['code' => $result_array['code'],'message' => $result_array['message']];
        }

        return ['code' => 200, 'message' => 'ok'];

    }


    /**
     * 会员账户余额消费
     * @param array  $args_array
     *               $args_array['account_accesscode']     账号识别码                      必须
     *               $args_array['account_accesstype']    账户识别码类型 0-卡号  2-会员号   必须
     *                   $args_array['password']              支付密码                         必须
     *               $args_array['amount']               消费金额                          必须
     * @return array
     */
    public function consumption( $args_array ){


        if ( !isset($args_array['cardNo']) || empty($args_array['cardNo']) ) {
            return [ 'code' => 400, 'message' => '卡号不能为空' ];
        }

        if (!isset($args_array['password']) || empty($args_array['password'])) {
            return [ 'code' => 400 , 'message' => '账户密码不能为空' ];
        }

        if (!isset($args_array['amount']) || !$args_array['amount'] ) {
            return [ 'code' => 400 , 'message' => '消费金额不能为空' ];
        }

        $this->card_no = $args_array['cardNo'];

        //调整组织代码
        $this->adjustOrgCode($args_array);

        //请求地址
        $request_url = $this->http_url . 'desaccount/pay';

        //url参数
        $business_params = [
            'xid' => time(),
            'orgcode'  => $this->org_code,
            'account_accesscode'  => $args_array['cardNo'],
            'account_accesstype'  => $this->account_access_type,
            'passsword'  => $args_array['password'],
            'occur'  => $args_array['amount'],
        ];

        $request_res = $this->request( $request_url, 'consumption', $business_params, '', 'post:json' );

        if ( $request_res['code'] != 200 ) {
            return ['code' => $request_res['code'] , 'message' =>  $request_res['message']];
        }

        $balance = 0;

        if ( $request_res['data'] ) {
            $balance = $request_res['data'];
        }

        return ['code' => 200, 'message' => 'ok', 'data' => [ 'balance' => $balance ]];

    }



    /**
     * 会员修改支付密码接口
     * @param array     $args_array                            请求参数
     *        String    $args_array['cardNo']                  外部交易号                     必选
     * @return array
     */
    public function changePassword ( $args_array ) {

        if (!isset($args_array['cardNo']) || empty($args_array['cardNo'])) {
            return array('code'=>400 , 'message'=>'卡号不能为空');
        }

        if (!isset($args_array['new_password']) || empty($args_array['new_password'])) {
            return array('code'=>400 , 'message'=>'新密码不能为空');
        }

        $this->card_no = $args_array['cardNo'];

        //请求地址
        $request_url = $this->http_url . 'password/change_pay_password';

        //调整组织代码
        $this->adjustOrgCode($args_array);

        //设置接口请求参数
        $business_params = array(
            'xid' => time(),
            'orgcode' => $this->org_code,
            'account_accesscode' => (string)$args_array['cardNo'],
            'account_accesstype' => $this->account_access_type,
            'new_password' => $args_array['new_password'],
            'old_password' =>isset($args_array['old_password']) ? $args_array['old_password'] : ''
        );

        $request_res =  $this->request($request_url,'changePassword',$business_params,'','post:json');

        if ( $request_res['code'] != 200 ) {
            return ['code' => $request_res['code'], 'message' => $request_res['message']];
        }

        return ['code' => 200, 'message' => 'ok' ];

    }



    /**
     * 会员账户余额变更记录
     * @param  array	$args_array	            请求参数
     *         string	$args_array['cardNo']   卡号               必传
     *         int      $args_array['page']      页码,第一页默认0   必传
     *         int      $params['rp']             每页条数           可填
     *
     * @return array
     */
    public function accountLogs( $args_array ){


        //校验参数
        if (!isset($args_array['cardNo']) || empty($args_array['cardNo'])) {
            return [ 'code'=>400 , 'message'=>'卡号不能为空' ];
        }

        $this->card_no = $args_array['cardNo'];

        //设置接口url请求参数
        $business_params = [
            'begin_trandate' => isset($args_array['begin_trandate']) ? $args_array['begin_trandate'] : '2015-01-01',
            'end_trandate'   => isset($args_array['end_trandate']) ? $args_array['end_trandate'] : date('Y-m-d'),
            'origincode'     => $args_array['cardNo'],
            'appname'        => $this->app_name,                 //应用名称,定值
        ];

        //请求地址
        $request_url = $this->http_url."desaccounthst/query";

        //请求参数
        $request_params = [
            'orders' => [
                [
                    'field'=>'tranTime',
                    'direction'=>'desc'
                ]
            ],
            'pageSize' => !empty($args_array['pageSize']) ? $args_array['pageSize'] : 10,     //每页个数
            'page' => !empty($args_array['page']) ? intval($args_array['page'])-1 : 0        //页码
        ];

        //调用接口
        $request_res =  $this->request( $request_url, 'accountLogs', $business_params , $request_params , 'post:json' );

        if ( $request_res['code'] != 200 ) {
            return ['code' => $request_res['code'] , 'message' =>  $request_res['message']];
        }

        //页码
        $return_array = [
            'page'  => intval($request_res['data']['paging']['page'])+1,
            'pageSize'  => $request_res['data']['paging']['pageSize'],
            'pageCount'=>$request_res['data']['paging']['pageCount'],
            'count' => !empty($request_res['data']['paging']['recordCount']) ? $request_res['data']['paging']['recordCount'] : 0,
        ];

        foreach( $request_res['data']['records'] as $key=>$value ){
            $return_array['data'][] = [
                'createTime' => $value['created'],                                             //创建时间
                'tranTime ' => isset($value['tranTime'])?$value['tranTime']:'',                //交易时间
                'tranId ' => isset($value['tranId'])?$value['tranId']:'',                      //交易号
                'terminalId ' => isset($value['terminalId'])?$value['terminalId']:'',          //终端id
                'cardNum' => $value['cardNum'],                                                //卡号
                'cardNo' => $value['cardNum'],                                                 //卡号
                'changeAccount' => abs( $value['occur'] ),                                      //增加或减少的余额
                'action' => !empty($value['action'])?$value['action']:'',                       //消费代码
                'remark' => !empty($value['action'])?$value['action']:'',                       //消费名称
                'stat' => $value['occur']>0 ? 1: 0 ,                                            //状态 ,1:增加余额  0: 减少余额
                'changeType' => $value['occur']>0 ? 1: 0                                        //状态 ,1:增加余额  0: 减少余额
            ];
        }

        return ['code' => 200, 'messaege'=> 'ok', 'data' => $return_array];

    }




    /**
     * 传送线上绑定粉丝
     * @param $args_array
     *  @return array
     */
    public function deliverBindCust($args_array){

        if (!isset($args_array['openId']) || empty($args_array['openId'])) {
            return [ 'code'=>400 , 'message'=>'openId不能为空' ];
        }
        if (!isset($args_array['cardNo']) || empty($args_array['cardNo'])) {
            return [ 'code'=>400 , 'message'=>'cardNo不能为空' ];
        }

        $this->card_no = $args_array['cardNo'];

        $this->adjustOrgCode($args_array);

        //会员绑定参数
        $request_params = [
            'xid'        => time(),
            'storeCode'  => $this->org_code,
            'openId'     => $args_array['openId'],
            'cardId'     => $this->card_id,
            'memberCode' => $args_array['cardNo']
        ];

        //请求地址
        $request_url = $this->http_url."wx/save_extopencard";

        //调用接口
        $request_res = $this->request( $request_url, 'save_extopencard', '' , $request_params, 'post:json' );

        if ( $request_res['code'] != 200 ) {
            return ['code' => $request_res['code'] , 'message' =>  $request_res['message']];
        }

        return ['code' => 200, 'message' => 'ok'];

    }



    /**
     * 充值准备接口
     * @param $args_array
     * @return array
     */
    public function rechargePrepare( $args_array ){

        if (isset($args_array['cardNo']) && empty($args_array['cardNo'])) {
            return [ 'code'=>400 , 'message'=>'卡号不能为空' ];
        }

        if (!isset($args_array['amount']) || !$args_array['amount']) {
            return [ 'code' => 400 , 'message' => '充值金额不能为空' ];
        }

        if (!isset($args_array['tranId']) || !$args_array['tranId'] ) {
            $args_array['tranId'] = time();
        }

        $this->card_no = $args_array['cardNo'];

        //调整组织代码
        $this->adjustOrgCode($args_array);

        //准备充值接口
        $prepare_args = [
            'accountAccessCode' => $args_array['cardNo'],
            'accountAccessType' => $this->account_access_type,
            'orgCode' => $this->org_code,
            'tranId' => isset($args_array['tranId'])? $args_array['tranId'] : time(),
            'occur' => $args_array['amount'],
            'realPay' => $args_array['amount'],
            'tranTime' => date('Y-m-d H:i:s'),
            'xid' => time(),
        ];

        $request_res =  $this->request( $this->http_url . 'accountcashdeposit/prepare', 'prepare', array(), $prepare_args, 'post:json' );

        if ( $request_res['code'] != 200 ) {
            return ['code' => $request_res['code'] , 'message' =>  $request_res['message']];
        }

        return ['code' => 200, 'message' => 'ok'];

    }



    /**
     * 充值确认接口
     * @param $args_array
     * @return array
     */
    public function rechargeConfirm( $args_array ){

        if (isset($args_array['cardNo']) && empty($args_array['cardNo'])) {
            return [ 'code'=>400 , 'message'=>'卡号不能为空' ];
        }

        if (!isset($args_array['amount']) || !$args_array['amount']) {
            return [ 'code' => 400 , 'message' => '充值金额不能为空' ];
        }

        if (!isset($args_array['tranId']) || !$args_array['tranId']) {
            $args_array['tranId'] = time();
        }

        $this->card_no = $args_array['cardNo'];

        //调整组织代码
        $this->adjustOrgCode($args_array);

        //充值确认接口
        $recharge_args = [
            'orgCode'  => $this->org_code,
            'prepareTranId'  => $args_array['tranId'],
            'tranTime'  => date('Y-m-d H:i:s'),
            'payLines'  => [
                [
                    'payCode' => 'cash',        //cash 约定好定值
                    'payName' => 'cash',
                    'pay' => $args_array['amount']
                ]
            ]
        ];

        $request_res =  $this->request( $this->http_url . '/accountcashdeposit/confirm', 'recharge', array(), $recharge_args, 'post:json' );

        if ( $request_res['code'] != 200 ) {
            return ['code' => $request_res['code'] , 'message' =>  $request_res['message']];
        }

        return ['code' => 200, 'message' => 'ok' ];

    }


    /**
     * 根据会员代码查询会员资料
     * @param $args_array
     * $args_array['cardNo']  卡号  必须
     * @return array
     */
    public function queryBuId($args_array) {

        if( !isset($args_array['cardNo']) || empty($args_array['cardNo']) ){
            return [ 'message'=>'会员卡号不能为空' , 'code'=>401 ];
        }

        $this->card_no = $args_array['cardNo'];

        //请求地址
        $request_url = $this->http_url."member/" . $args_array['cardNo'];

        //调用接口
        $request_res = $this->request($request_url , 'queryById' , '' , '' , 'get');

        if ( $request_res['code'] != 200 ) {
            return ['code' => $request_res['code'] , 'message' =>  $request_res['message']];
        }

        return ['code' => 200, 'message' => 'ok', 'data' => $request_res['data'] ];

    }


    /**
     * 根据卡号查询会员资料
     * @param $args_array
     * $args_array['cardNo']  卡号  必须
     * @return array
     */
    public  function queryByCardNo ( $args_array ) {

        if( !isset($args_array['cardNo']) && empty($args_array['cardNo']) ){
            return [ 'message'=>'卡号不能为空' , 'code'=>400 ];
        }

        $this->card_no = $args_array['cardNo'];

        //请求地址
        $request_url = $this->http_url."member/query_by_cardnum";

        //设置接口请求参数
        $business_params = [
            'cardnum'=>$args_array['cardNo']
        ];

        //调用接口
        $request_res =  $this->request( $request_url, 'queryByCardNo', $business_params , '' , 'get' );

        if ( $request_res['code'] != 200 ) {
            return ['code' => $request_res['code'] , 'message' =>  $request_res['message']];
        }

        return [
            'code' => 200,
            'message' => 'ok',
            'data' => [
                'cardNo'     => $request_res['data']['originCode '],            //卡号
                'cardType'   => $request_res['data']['memberGrade']['code'],    //卡类型code  9999（美心钻石卡）、8888（美心黑金卡）、6666（美心金卡）、3333（美心银卡）、2222（美心绿卡）
                'cardName'   => $request_res['data']['memberGrade']['name'],    //卡类型名称
                'memberName' => $request_res['data']['name'],                   //会员名称
                'memberCode' => $request_res['data']['code']                    //线下会员号
            ]
        ];

    }




}